<template>
  <div class="customer">
    <ListTab
      v-model="tabStatus"
      :mode="0"
      :tabs="tabs"
      :mode-list="modeList"
      :show-header="!showMobilePage"
      is-table
      @tabClick="handleTabClick" />
    <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="table-list min-fill-page">
      <dataDisplay v-if="clientData" :data-list="dataList" type="oneCell" style="margin-bottom: 20px;" class="mobile-data" @handelItemClick="dataDisplayItemClick"/>
      <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
        <FilterInput ref="filterInput" v-model="filterInput" :filter-list="filterList" is-show-config show-search-btn class="FilterTool" @handelClick="queryClick" @queryEmpty="queryEmpty" @filterTagStatus="filterTagStatus" />
        <div style="position: absolute;left: 509px;top: 6px;display:flex;align-items:center;">
          <el-checkbox v-model="filterInput.preciseQuery" :true-label="1" :false-label="0" style="margin-right: 20px;" @change="queryClick">
            精准查询客户<tipIcon content="当勾选时，将精准匹配客户名称，可查询自己没有查看权限的客户历史对接情况" class="ml5" max-width="200px" style="position: relative;top: 2px;"/>
          </el-checkbox>
        </div>
        <div class="opeator-bar" style="align-items: center;display: flex;">
          <createBtn v-if="hasRouteAuth('crm:customer:add')" style="margin-right: 10px;" @click.native="handleCreate" />
          <PlainCreateBtn v-if="hasRouteAuth('crm:customer:add')" class="create-btn" style="height:32px;margin: 0 10px 0 0;" @click.native="toCreateApproval">协作申请</PlainCreateBtn>
          <btnGroup
            v-if="hasRouteAuth('crm:customer:export') || hasRouteAuth('crm:customer:import')"
            ref="btnGroupRef"
            :list="[
              {label:'导入', importApi:'/admin/client/import', callback:fetchData, type: 'import',auth:hasRouteAuth('crm:customer:import') },
              {label:'导出', exportApi:'/admin/client/export', exportName:'客户明细', beforeExport: exportBeforeExport, type: 'export', auth: hasRouteAuth('crm:customer:export')},
            ]"
          />
        </div>
      </div>
      <div v-loading="listLoading" style="min-height: 100px;">
        <u-table
          v-if="list.items.length > 0"
          ref="customerTableRef"
          :data="list.items"
          :row-class-name="tableRowClassName"
          :height="setTableHeight"
          :row-height="rowHeight()"
          :border="true"
          beautify-table
          header-drag-style
          use-virtual
          class="fb-table"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
          @sort-change="sortMethod"
          @select="selectTable"
          @select-all="selectTable">
          <u-table-column
            :fixed="selectFixed"
            align="center"
            type="selection"
            width="50"/>
          <u-table-column :fixed="selectFixed" align="left" label="客户名称" min-width="264" prop="clientName" sortable="custom">
            <template slot-scope="scope">
              <div class="resource-name-container">
                <ToolTip :content="scope.row.clientName" is-can-click @handelClick="toDetail(scope.row)" />
                <a :href="'https://www.tianyancha.com/search?key=' + scope.row.clientName" class="search-resource-container" target="_blank"><img :src="searchresource" class="search-resource" alt=""></a>
              </div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="客户等级" width="120" prop="clientLevel" sortable="custom" class-name="cell-bg-box">
            <template slot-scope="scope">
              <EditLevelAndStatus :row="scope.row" :options="clientLevelOptions" type="level" @openEditLevel="openEditLevel" @refresh="fetchData" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="客户状态" min-width="120" prop="clientStatusStr" sortable="custom" class-name="cell-bg-box">
            <template slot-scope="scope">
              <EditLevelAndStatus :row="scope.row" :options="clientStatusList" type="status" @refresh="fetchData" />
            </template>
          </u-table-column>
          <u-table-column align="right" label="交易总额(元)" min-width="150" prop="taxAmount" sortable="custom">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.taxAmount" :price="scope.row.taxAmount / 100" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="核销情况" min-width="180" prop="returnMoneyNum" sortable="custom">
            <template slot-scope="scope">
              <el-progress
                v-if="scope.row.returnMoney >= 100"
                :percentage="100"
                :stroke-width="10"
                :format="() => scope.row.returnMoney + '%'"
                :title="scope.row.returnMoney + '%'"
                class="progress-cell"
                color="#31cc9c" />
              <el-progress
                v-else-if="scope.row.returnMoney && scope.row.returnMoney >= 0"
                :percentage="scope.row.returnMoney"
                :stroke-width="10"
                :format="() => scope.row.returnMoney + '%'"
                :title="scope.row.returnMoney + '%'"
                class="progress-cell"
                color="#406eff" />
              <el-progress
                v-else
                :percentage="0"
                :stroke-width="10"
                :format="() => (scope.row.returnMoney || 0) + '%'"
                :title="(scope.row.returnMoney || 0) + '%'"
                class="progress-cell"
                color="#dde1ea" />
            </template>
          </u-table-column>
          <u-table-column align="right" label="可核销流水(元)" min-width="150" prop="writeOffFlow">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.writeOffFlow" :price="scope.row.writeOffFlow / 100" />
            </template>
          </u-table-column>
          <u-table-column align="right" label="欠款金额(元)" width="150" prop="owePrice" sortable="custom">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.owePrice" :price="scope.row.owePrice / 100" />
            </template>
          </u-table-column>
          <u-table-column align="right" label="额度上限(元)" width="150" prop="priceCeiling" sortable="custom">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.priceCeiling" :price="scope.row.priceCeiling / 100" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="欠款订单数" width="120" prop="oweOrder" sortable="custom">
            <template slot-scope="scope">
              {{ scope.row.oweOrder | moneyFilter }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="逾期情况" min-width="110" prop="overdueStatus" sortable="custom">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.overdueStatus | overdueStatusState">
                <div class="flex-center">
                  <div :class="`color-${scope.row.overdueStatus}`" class="dot"/>
                  <div :style="{ color: scope.row.overdueStatus === -1 ? '#AEB6C7' : '#333' }">
                    {{ scope.row.overdueStatus | overdueStatusState }}
                  </div>
                </div>
              </ToolTip>
            </template>
          </u-table-column>
          <u-table-column align="left" label="逾期欠款订单数" min-width="145" prop="overdueOrder" sortable="custom">
            <template slot-scope="scope">
              {{ scope.row.overdueOrder | moneyFilter }}
            </template>
          </u-table-column>
          <u-table-column align="right" label="逾期欠款金额(元)" min-width="160" prop="overduePrice" sortable="custom">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.overduePrice" :price="scope.row.overduePrice / 100" />
            </template>
          </u-table-column>
          <u-table-column align="right" label="剩余欠款额度(元)" min-width="160" prop="balanceAmount" sortable="custom">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.balanceAmount" :price="scope.row.balanceAmount / 100" />
            </template>
          </u-table-column>
          <u-table-column align="right" label="欠款账期(天)" min-width="130" prop="accountPeriod" sortable="custom">
            <template slot-scope="scope">
              <div v-if="scope.row.accountPeriod === null" style="color: #AEB6C7; text-align: left">未设等级</div>
              <ToolTip v-else :content="scope.row.accountPeriod" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="编号" width="80">
            <template slot-scope="scope">
              {{ scope.row.id }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="客户类型" width="100">
            <template slot-scope="scope">
              {{ scope.row.clientType | clientStatusFilter }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="所属部门" min-width="130">
            <template slot-scope="scope">
              <ToolTip v-if="scope.row.department && scope.row.department.length" :content="(scope.row.attributionMatrixFullName || scope.row.department) | formatTag">
                <span class="ellipsisOne">{{ scope.row.department | formatTag }}</span>
              </ToolTip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="所属集团" min-width="130">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.group" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="标签" min-width="130">
            <template slot-scope="scope">
              <TagSelect v-model="scope.row.tag" mode="list" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="实际客户名称" min-width="120">
            <template slot-scope="scope">
              <div>{{ scope.row.actualClientRequired ? '必填' : '非必填' }}</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="销售" min-width="110">
            <template slot-scope="scope">
              <CheckUserInfo
                v-if="handelSales(scope.row)"
                :user-list="handelSales(scope.row)"
                :multiple="handelSales(scope.row).length > 1"
                :user-id="handelSales(scope.row).length === 1?handelSales(scope.row)[0].id:null"
                :label="handelSales(scope.row).length === 1?handelSales(scope.row)[0].userName:null"
              />
              <ToolTip v-else :content="scope.row.sale" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="备注" min-width="140">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.remark" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="对账进度" min-width="180" prop="checkProgress" sortable="custom">
            <template slot-scope="scope">
              <span v-if="scope.row.taxAmount === 0 || (scope.row.checkProgress !== 0 && !scope.row.checkProgress)">--</span>
              <el-progress
                v-else
                :percentage="scope.row.checkProgress"
                :stroke-width="10"
                :format="() => scope.row.checkProgress + '%'"
                :title="scope.row.checkProgress + '%'"
                :color="`${scope.row.checkProgress === 100 ? '#31CC9C' : '#406eff'}`"
                class="progress-cell"
              />
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建时间" min-width="165" prop="createTime" sortable="custom">
            <template slot-scope="scope">
              {{ scope.row.createTime | standardFormat('YYYY/MM/DD HH:mm') }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建人" min-width="80">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.createUserId" :label="scope.row.createName" :user-id="scope.row.createUserId" />
              <ToolTip v-else :content="scope.row.createName" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="跟进人" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.followName"/>
            </template>
          </u-table-column>
          <u-table-column :width="operateWidth" fixed="right" align="left" label="操作">
            <template slot-scope="scope">
              <div v-if="!showMobilePage" style="display:flex;">
                <div class="button-text" @click="toDetail(scope.row)">查看</div>
                <el-dropdown trigger="click">
                  <div class="el-dropdown-link" style="cursor:pointer;">
                    <div class="button-text">更多 <i class="el-icon-arrow-down"/></div>
                  </div>
                  <el-dropdown-menu slot="dropdown" style="margin-top:-24px;margin-right:15px;padding: 0;">
                    <el-dropdown-item v-if="hasRouteAuth('crm:customer:edit')" style="width:100px;text-align: center" @click.native="toEdit(scope)">
                      <div>编辑</div>
                    </el-dropdown-item>
                    <el-dropdown-item style="width:100px;text-align: center" @click.native="createSettleDialog(scope.row.clientName)">
                      <div>创建结算</div>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="scope.row.createName === $store.getters.userName || hasRouteAuth('crm:customer:delete')" style="width:100px;text-align: center" @click.native="delCustomer(scope.row.id)">
                      <div>删除</div>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              <tableOperateBtn v-else>
                <el-dropdown-item style="width:90px;text-align: center" @click.native="toDetail(scope.row)">
                  <div>查看</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="hasRouteAuth('crm:customer:edit')" style="width:90px;text-align: center" @click.native="toEdit(scope)">
                  <div>编辑</div>
                </el-dropdown-item>
                <el-dropdown-item style="width:90px;text-align: center" @click.native="createSettleDialog(scope.row.clientName)">
                  <div>创建结算</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.createName === $store.getters.userName || hasRouteAuth('crm:customer:delete')" style="width:90px;text-align: center" @click.native="delCustomer(scope.row.id)">
                  <div>删除</div>
                </el-dropdown-item>
              </tableOperateBtn>
            </template>
          </u-table-column>
        </u-table>
        <div v-else-if="preciseData.length > 0" class="precise-container">
          <div class="precise-img-tip">
            <img :src="withoutPermission">
            <p>暂无该客户查看权限</p>
          </div>
          <div class="precise-data">
            <p class="precise-text">
              该客户的历史数据如下，你可通过<span class="light-text" @click="handleCreate(1)">创建该客户</span>获取该客户查看及使用权限<span class="gray-text">（注：无法查看历史联系人及交易数据）</span>
            </p>
            <div class="precise-table">
              <el-table
                :data="preciseData"
                style="width: 100%">
                <el-table-column label="客户名称" min-width="120">
                  <template slot-scope="scope">
                    <ToolTip :content="scope.row.clientName" />
                  </template>
                </el-table-column>
                <el-table-column prop="clientStatusStr" label="客户状态" />
                <el-table-column
                  prop="address"
                  label="合同">
                  <template slot-scope="scope">
                    <span>{{ scope.row.contractSignStatus ? '已签订' : '未签订' }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="订单">
                  <template slot-scope="scope">
                    <span>{{ scope.row.taxAmount ? '已下单' : '未下单' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="销售">
                  <template slot-scope="scope">
                    <CheckUserInfo
                      v-if="handelSales(scope.row)"
                      :user-list="handelSales(scope.row)"
                      :multiple="handelSales(scope.row).length > 1"
                      :user-id="handelSales(scope.row).length === 1?handelSales(scope.row)[0].id:null"
                      :label="handelSales(scope.row).length === 1?handelSales(scope.row)[0].userName:null"
                    />
                    <ToolTip v-else :content="scope.row.sale" />
                  </template>
                </el-table-column>
                <el-table-column label="跟进人">
                  <template slot-scope="scope" >
                    <ToolTip :content="scope.row.followName" />
                  </template>
                </el-table-column>
                <el-table-column label="创建人">
                  <template slot-scope="scope">
                    <CheckUserInfo v-if="scope.row.createUserId" :label="scope.row.createName" :user-id="scope.row.createUserId" />
                    <ToolTip v-else :content="scope.row.createName" />
                  </template>
                </el-table-column>
                <el-table-column label="创建时间" min-width="150">
                  <template slot-scope="scope">
                    <span>{{ scope.row.createTime | standardFormat('YYYY/MM/DD HH:mm') }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
        <empty-placeholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
      </div>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <el-pagination
          v-show="list.total > 0"
          :current-page="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :small="true"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <fixed-pagination>
        <template v-if="!showMobilePage">
          <MoreOpeator
            v-if="hasRouteAuth('crm:customer:updateSales')"
            :list="[
              {label: '更新客户销售', handelClick: batchUpdate, disabled:isUpdating, loading:isUpdating},
              {label: '更新客户部门', handelClick: batchUpdateDepartment, disabled:isUpdateDepartment, loading:isUpdateDepartment },
            ]"
            label="批量操作"
            style="margin-right:16px;"
          />
          <SelectionNum :select-item="multipleSelectionAll" style="flex:1;" @clearMixinSelection="clearMixinSelection" />
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </template>
        <template v-else>
          <FilterInput ref="filterInput" v-model="filterInput" :filter-list="filterList" show-mobile-icon is-show-config show-search-btn class="FilterTool" @handelClick="queryClick" @queryEmpty="queryEmpty" @filterTagStatus="filterTagStatus">
            <div slot="checkGroup">
              <el-checkbox v-model="filterInput.preciseQuery" :true-label="1" :false-label="0" style="margin-right: 20px;" @change="queryClick">
                精准查询客户<tipIcon content="当勾选时，将精准匹配客户名称，可查询自己没有查看权限的客户历史对接情况" class="ml5" max-width="200px" style="position: relative;top: 2px;"/>
              </el-checkbox>
            </div>
          </FilterInput>
          <div>
            <MoreOpeator
              :list="[
                {label: '更新客户销售', handelClick: batchUpdate, disabled:isUpdating, loading:isUpdating, auth: hasRouteAuth('crm:customer:updateSales')},
                {label: '更新客户部门', handelClick: batchUpdateDepartment, disabled:isUpdateDepartment, loading:isUpdateDepartment },
                {label: '查看联系人明细', handelClick: toContact},
                {label:'导入', importApi:'/admin/client/import', callback:fetchData, type: 'import',auth:hasRouteAuth('crm:customer:import') },
                {label:'导出', exportApi:'/admin/client/export', exportName:'客户明细', beforeExport: exportBeforeExport, type: 'export', auth: hasRouteAuth('crm:customer:export')},
              ]"
              show-mobile-icon
              label="批量操作"
            />
          </div>
          <createBtn v-if="hasRouteAuth('crm:customer:add')" mobile-table style="margin-right:14px;" @click.native="handleCreate" />
        </template>
      </fixed-pagination>
    </div>
    <createSettle ref="createRef" />
    <CreateApproval ref="CreateApprovalRef" />
    <LevelInfo
      ref="levelInfoRef"
      target="_blank"
      @fetchData="fetchData" />
  </div>
</template>

<script>
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import EditLevelAndStatus from './module/EditLevelAndStatus';
import { getClientStatus } from '@/api/select';
import { hasRouteAuth } from '@/utils/permission';
import CreateApproval from './cooperation/createApproval';
import { getList, getClientDashboard, delClient, batchUpdate, getUpdateStatus, getClientGroup, getLevelList, batchUpdateDepartment } from '@/api/customer';
import { getDepartmentAll, getTagAll } from '@/api/config';
import { TAG_MODULES } from '@/utils/const';
// 跨页选中逻辑
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';

import { standardFormat } from '@/filters/date';
import { clientStatusFilter, clientStatus, returnMoneyState, overdueStatusState } from '@/filters/status';
import { getDeptFullName, formatTag } from '@/filters/dept';
import { priceFormat, moneyFilter } from '@/filters/number';

import createSettle from '@/components/Customer/createSettle';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import createBtn from '@/components/Common/baseComponent/createBtn';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import ListTab from '@/components/ListTab';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import LevelInfo from '@/components/Customer/setAccountPeriod';
import TagSelect from '@/components/Common/tagSelect';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
import { showModal } from '@/utils/message';
import searchresource from '@/assets/search-resource.png';
import setting from '@/assets/setting.png';
import icon_16 from '@/assets/dataDisplay/icon_16.png';
import icon_17 from '@/assets/dataDisplay/icon_17.png';
import icon_18 from '@/assets/dataDisplay/icon_18.png';
import icon_19 from '@/assets/dataDisplay/icon_19.png';
import icon_20 from '@/assets/dataDisplay/icon_20.png';
import icon_21 from '@/assets/dataDisplay/icon_21.png';
import icon_22 from '@/assets/dataDisplay/icon_22.png';
import icon_23 from '@/assets/dataDisplay/icon_23.png';
import icon_46 from '@/assets/dataDisplay/icon_46.png';
import withoutPermission from '@/assets/client/withoutPermission.png';
import ElMessage from '@/utils/message';
import { LEVEL_CHANGE_TYPE } from '@/utils/const/customer';

export default {
  filters: {
    standardFormat,
    clientStatusFilter,
    clientStatus,
    priceFormat,
    moneyFilter,
    returnMoneyState,
    getDeptFullName,
    overdueStatusState,
    formatTag
  },
  components: {
    EmptyPlaceholder, createSettle, dataDisplay, EditLevelAndStatus,
    createBtn, btnGroup, ListTab, MoreOpeator, CreateApproval, LevelInfo, TagSelect
  },
  mixins: [tableSelections, TableAdaptive, mobileTable],
  data() {
    return {
      TAG_MODULES,
      setting,
      searchresource,
      withoutPermission,
      sortType: '',
      sortName: '',
      statisticType: '',
      filterInput: {},
      ids: '',
      clientData: {},
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true,
        totalAmount: '',
        amount: {}
      },
      clientStatusOptionData: [],
      clientStatusList: [],
      perPage: 20,
      listLoading: true,
      page: 1,
      tableRefName: 'customerTableRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      deptTreeList: [],
      tagTreeList: [],
      isUmyTable: true,
      isUpdating: false,
      isUpdateDepartment: false,
      timer: null,
      groupList: [],
      preciseData: [],
      clientLevelOptions: [],
      tabs: [
        { id: -1, name: '全部', num: 0 },
        { id: 0, name: '无逾期', num: 0 },
        { id: 1, name: '有逾期', num: 0 },
        { id: 2, name: '未设等级', num: 0 }
      ],
      tabStatus: -1
    };
  },
  computed: {
    modeList() {
      return [
        { mode: 0, name: '客户', handleClick: () => {} },
        { mode: 1, name: '联系人', handleClick: this.toContact }
      ];
    },
    dataList() {
      const clientData = this.clientData;
      return [
        { label: '订单总金额', data: clientData['orderTotalPrice'] / 100, tooltip: '所有客户订单的总额', isCanFilter: false, icon: icon_16 }, // 该客户的所有订单总额
        { label: '核销总额', data: clientData['returnMoneyTotal'] / 100, tooltip: '所有订单已完成流水', isCanFilter: false, icon: icon_17 },
        { label: '欠款客户数', data: clientData['oweClientNum'], tooltip: '含有待核销订单的客户', key: 'oweClientNum', isCanFilter: true, icon: icon_18, isMoney: false },
        { label: '逾期客户数', data: clientData['overdueCustNum'], tooltip: '含有逾期待核销的客户', key: 'overdueCustNum', isCanFilter: true, icon: icon_19, isMoney: false },
        { label: '欠款订单数', data: clientData['oweOrderNum'], tooltip: '未完全核销的订单数量', isCanFilter: false, icon: icon_20, isMoney: false },
        { label: '欠款金额', data: clientData['owePrice'] / 100, tooltip: '订单待核销总额', isCanFilter: false, icon: icon_21 },
        { label: '逾期欠款订单数', data: clientData['overdueOrderNum'], tooltip: '该客户订单已超过账期的包含未核销和部分核销订单数', isCanFilter: false, icon: icon_22, isMoney: false },
        { label: '逾期欠款金额', data: clientData['overduePrice'] / 100, tooltip: '该客户订单已超过账期的总待核销金额', isCanFilter: false, icon: icon_23 },
        { label: '综合对账进度', data: clientData['accountProgress'] ? (clientData['accountProgress'] * 100).toFixed(2) : '', tooltip: '已核销订单数/总订单数', isCanFilter: false, icon: icon_46, unit: '%' }
      ];
    },
    filterList() {
      return [
        { keyword: 'clientName', name: '客户名称', type: 'input', labelWidth: '96px' },
        { keyword: 'contactPerson', name: '联系人', type: 'input', labelWidth: '96px' },
        { keyword: 'createName', name: '创建人', type: 'input', labelWidth: '96px' },
        { keyword: 'payer', name: '付款人', type: 'input', labelWidth: '96px' },
        { keyword: 'payAccount', name: '付款账号', type: 'input', labelWidth: '96px' },
        // { keyword: 'sale', name: '销售', type: 'inputSearch', searchkeyword: 'name', tagName: 'saleName', labelWidth: '70px' },
        { keyword: 'sale', name: '销售', type: 'inputSearch', tagName: 'saleName', labelWidth: '96px' },
        { keyword: 'contactCreator', name: '联系人创建人', type: 'input', labelWidth: '96px' },
        { keyword: 'contactCollaborator', name: '联系人协作人', type: 'inputSearch', tagName: 'contactCollaboratorName', labelWidth: '96px' },
        { keyword: 'remark', name: '备注', type: 'input', labelWidth: '96px' },
        { keyword: 'batchClientName', name: '批量搜索客户名称', labelWidth: '96px', type: 'input', inputType: 'textarea',
          lengthLimit: false, placeholder: '可通过粘贴快速填写客户名称，每行代表一个客户名称' },
        { keyword: 'taxAmount', name: '交易总额', type: 'inputRange', labelWidth: '96px' },
        { keyword: 'checkProgress', name: '对账进度', min: 0, max: 100, startPlaceholder: '开始进度', endPlaceholder: '结束进度', unit: '%', type: 'inputRange', labelWidth: '96px' },
        { keyword: 'writeOffFlow', name: '可核销流水', type: 'inputRange', startPlaceholder: '最低金额', endPlaceholder: '最高金额', labelWidth: '96px' },
        { keyword: 'owePrice', name: '欠款金额', type: 'inputRange', startPlaceholder: '最低金额', endPlaceholder: '最高金额', labelWidth: '96px' },
        { keyword: 'oweOrder', name: '欠款订单数', type: 'inputRange', onlyInteger: true, startPlaceholder: '最低数值', endPlaceholder: '最高数值', labelWidth: '96px' },
        { keyword: 'overdueOrder', name: '逾期欠款订单数', type: 'inputRange', onlyInteger: true, startPlaceholder: '最低数值', endPlaceholder: '最高数值', labelWidth: '96px' },
        { keyword: 'overduePrice', name: '逾期欠款金额', type: 'inputRange', startPlaceholder: '最低金额', endPlaceholder: '最高金额', labelWidth: '96px' },
        { keyword: 'balanceAmount', name: '剩余欠款额度', type: 'inputRange', startPlaceholder: '最低额度', endPlaceholder: '最高额度', labelWidth: '96px' },
        { keyword: 'accountPeriod', name: '欠款账期', onlyInteger: true, type: 'inputRange', startPlaceholder: '最低天数', endPlaceholder: '最高天数', unit: '天', labelWidth: '96px' },
        { keyword: 'departmentId', name: '所属部门', type: 'cascaderSelect', childrenVal: 'children', strictly: true, options: this.deptTreeList },
        {
          keyword: 'clientType', name: '客户类型', type: 'select',
          options: [{ value: -1, label: '全部' }, { value: 0, label: '公司' }, { value: 1, label: '个人' }]
        },
        { keyword: 'clientStatus', name: '客户状态', type: 'select', options: this.clientStatusOptionData },
        {
          keyword: 'returnMoney', name: '核销情况', type: 'mulSelect',
          options: [{ value: -1, label: '全部' }, { value: 0, label: '待核销' }, { value: 1, label: '部分核销' }, { value: 2, label: '已完成' }]
        },
        {
          keyword: 'overdueStatus', name: '逾期情况', type: 'select',
          options: [{ value: -1, label: '全部' }, { value: 0, label: '无逾期' }, { value: 1, label: '有逾期' }, { value: 2, label: '未设等级' }]
        },
        { keyword: 'groupIds', name: '所属集团', valueName: 'id', labelName: 'name', type: 'select', options: this.groupList, isSearch: true },
        { keyword: 'createTime', name: '创建时间', timeType: 'daterange', type: 'rangeDate', labelWidth: '96px', startPlaceholder: '开始时间', endPlaceholder: '结束时间' },
        { keyword: 'orderTime', name: '下单日期', timeType: 'daterange', type: 'rangeDate', labelWidth: '96px' },
        { keyword: 'tag', name: '标签', type: 'cascaderSelect', childrenVal: 'item', options: this.tagTreeList, multiple: true, filterable: true, checkStrictly: false, collapseTags: true, valueName: 'name' },
        { keyword: 'clientLevel', name: '客户等级', type: 'mulSelect', options: this.clientLevelOptions }
      ];
    },
    rangeKeyArr() {
      return [
        { attr: 'createTime', start: 'createStart', end: 'createEnd', type: 'time' },
        { attr: 'orderTime', start: 'orderStartTime', end: 'orderEndTime', type: 'time' },
        { attr: 'taxAmount', start: 'taxAmountStart', end: 'taxAmountEnd', type: 'moneyFixed' },
        { attr: 'checkProgress', start: 'checkProgressStart', end: 'checkProgressEnd', type: 'number' },
        { attr: 'writeOffFlow', start: 'writeOffFlowStart', end: 'writeOffFlowEnd', type: 'moneyFixed' },
        { attr: 'owePrice', start: 'owePriceStart', end: 'owePriceEnd', type: 'moneyFixed' },
        { attr: 'oweOrder', start: 'oweOrderStart', end: 'oweOrderEnd', type: 'number' },
        { attr: 'overdueOrder', start: 'overdueOrderStart', end: 'overdueOrderEnd', type: 'number' },
        { attr: 'overduePrice', start: 'overduePriceStart', end: 'overduePriceEnd', type: 'moneyFixed' },
        { attr: 'balanceAmount', start: 'balanceAmountStart', end: 'balanceAmountEnd', type: 'moneyFixed' },
        { attr: 'accountPeriod', start: 'accountPeriodStart', end: 'accountPeriodEnd', type: 'number' }
      ];
    },
    arrayKeyArr() {
      return ['returnMoney', 'tag', 'clientLevel'];
    },
    showDel() {
      return function(row) {
        return row.createName === this.$store.getters.userName || this.hasRouteAuth('crm:customer:delete');
      };
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 205 : 302;
    }
  },
  watch: {
    isUpdating(newv, oldv) {
      this.clearTimer(newv, oldv);
    }
  },
  created() {
    this.getUpdateStatus(true);// 组件被销毁,如果处在更新状态重启定时器（如用户刷新页面）
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'editCustomer' || from.name === 'detailCustomer') {
      to.meta.isChange = true;
    } else {
      to.meta.isChange = false;
    }
    next();
  },
  activated() {
    this.queryDeptTreeList();
    this.queryTagTreeList();
    this.queryClientLevel();
    this.clientStatusOption();
    this.getGroupData();
    if (!this.$route.meta.isChange) {
      if (this.$route.query.batchClientName) {
        let { batchClientName } = this.$route.query;
        batchClientName = batchClientName.replace(/,/g, '\n');
        this.$set(this.filterInput, 'batchClientName', batchClientName);
      }
      const hasDefaultPresetFilter = this.$refs.filterInput && this.$refs.filterInput.hasDefaultPresetFilter;
      // 当预设的默认筛选且为第一次进入页面时，不请求数据（会在 filterTool 组件进行筛选）
      if (!this.list.isInit || !hasDefaultPresetFilter) {
        // this.queryEmpty();
        this.fetchData(true);
      }
    } else {
      if (this.clearMixinSelection) this.clearMixinSelection();
      if (this.list && this.list.items && this.list.items.length === 0) {
        this.fetchData(true);
      } else {
        this.fetchData();
      }
    }
  },
  methods: {
    hasRouteAuth,
    async getGroupData() {
      const { data } = await getClientGroup();
      this.groupList = data;
    },
    handleTabClick(id) {
      this.tabStatus = id;
      this.list = { items: [] };
      this.fetchData(true);
    },
    clientStatusOption() {
      getClientStatus().then((res) => {
        const clientStatusOption = res.data.map(item => {
          return {
            value: item.id,
            label: item.name
          };
        });
        this.clientStatusList = clientStatusOption;
        this.clientStatusOptionData = [{ value: -1, label: '全部' }, ...clientStatusOption];
      });
    },
    // 批量更新客户销售
    batchUpdate() {
      const title = `请确认是否更新客户销售`;
      showModal(title, '', {}).then(_ => {
        this.preciseData = [];
        this.isUpdating = true;
        // 开启轮询，获取更新情况
        if (!this.timer) {
          this.setTimer();
        }
        batchUpdate().then(res => {
          if (res.code !== 200) {
            this.$message.error(res.message);
            return;
          }
          this.$message.success('成功提交更新客户销售任务');
        }).catch(err => {
          console.log(err);
        });
      }).catch(_ => null);
    },
    batchUpdateDepartment() {
      showModal('请确认是否更新客户部门', '', {}).then(_ => {
        this.isUpdateDepartment = true;
        // const params = this.getParams();
        const params = {};
        if (this.multipleSelectionAll) params.ids = this.multipleSelectionAll.map(i => i.id).join(',');
        batchUpdateDepartment(params).then(res => {
          this.isUpdateDepartment = false;
          if (res.code !== 200) {
            this.$message.error(res.message);
            return;
          }
          this.$message.success(`更新${res.data}条数据成功`);
        }).catch(err => {
          this.isUpdateDepartment = false;
          console.log(err);
        });
      }).catch(_ => null);
    },
    // 获取更新状态
    getUpdateStatus(init = false) {
      getUpdateStatus().then(res => {
        this.isUpdating = res.data.isUpdating;
        if (init && this.isUpdating) {
          this.setTimer();
        }
      }).catch(err => {
        console.log(err);
      });
    },
    // 每隔一段时间去查询是否在更新信息
    setTimer(time = 1500) {
      this.timer = setInterval(() => {
        this.getUpdateStatus();
      }, time);
    },
    // 刷新列表，清除定时器
    clearTimer(newv, oldv) {
      if (oldv && !newv) { // true=>false
        if (!this.isUpdating) { // 两者都完成清除定时器
          clearInterval(this.timer);
          this.timer = null;
          this.$message.success('更新客户销售成功');
          this.fetchData();
        }
      }
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    dataDisplayItemClick(item) {
      const type = item.key;
      if (!item.isCanFilter) return;
      const filterLevel = this.$refs['filterInput'].level;
      if (filterLevel === 'normal') {
        this.$refs['filterInput'].changeLevel();
      }
      this.statisticType = type;
      const params = {};
      switch (type) {
        case 'oweClientNum':
          params.returnMoney = [0, 1];
          break;
        case 'overdueCustNum':
          params['overdueStatus'] = 1;
          break;
      }
      this.filterInput = params;
      this.fetchData();
    },
    getParams() {
      const params = JSON.parse(JSON.stringify(this.filterInput));
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      params.authControl = 1;
      params.tabStatus = this.tabStatus;
      delete params.saleName; // 删除筛选销售名称
      delete params.contactCollaboratorName;
      return params;
    },
    exportBeforeExport() {
      const params = this.getParams();
      if (this.multipleSelectionAll) params.ids = this.multipleSelectionAll.map(i => i.id).join(',');
      if (this.$refs.btnGroupRef) {
        this.$refs.btnGroupRef.btnExport(params);
      }
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = this.getParams();
      params.sortName = this.sortName;
      params.sortType = this.sortType;
      params.page = this.page;
      params.perPage = this.perPage;
      this.listLoading = true;
      params.authControl = 1;
      this.preciseData = [];
      this.getClientData(params);
      getList(params).then(({ data }) => {
        this.list = data;
        if (data.item) {
          this.preciseData.push(data.item);
        }
        this.ids = '';
        this.list.isInit = false;
        this.listLoading = false;
        if (this.setSelectRow) this.setSelectRow(data.items);
      }, result => {
        this.listLoading = false;
      }).catch(e => {
        console.error(e);
      });
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.filterInput = {};
      this.filterInput.preciseQuery = 0;
      if (this.clearMixinSelection) this.clearMixinSelection();
      this.queryClick();
    },
    toEdit(scope) {
      this.$router.push({
        name: 'editCustomer',
        params: { customerId: scope.row.id }
      });
    },
    createOrder() {
      this.$router.push({
        name: 'createCustomer'
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    // 选择表格
    tableSelectionChange(e) {
      this.ids = e.map(item => {
        return item.id;
      }).join(',');
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    rowClick(row, column, event) {
      if (column.label !== '操作' && column.label !== '客户名称') {
        this.$router.push({
          name: 'detailCustomer',
          params: { customerId: row.id }
        });
      }
    },
    toDetail(item) {
      this.$router.push({
        name: 'detailCustomer',
        params: { customerId: item.id, filterInput: this.filterInput }
      });
    },
    getClientData(data) {
      const params = _.cloneDeep(data);
      delete params.sortName;
      delete params.sortType;
      getClientDashboard(params).then(res => {
        if (res.code === 200) {
          this.clientData = res.data;
          this.tabs.forEach(i => {
            if (i.id === 1) {
              i.num = res.data.overdueCustNum;
            }
          });
        }
      }).catch(() => {
      });
    },
    createSettleDialog(clientName) {
      const data = {
        clientCompany: clientName
      };
      if (this.$refs.createRef) this.$refs.createRef.openDialog(data, false, true);
    },
    // 获取所属部门
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    queryTagTreeList() {
      const params = { type: this.TAG_MODULES.SETTLE_CUSTOMER };
      getTagAll(params).then(res => {
        this.tagTreeList = (res && res.data) || [];
        this.tagTreeList.forEach(item => {
          if (!item.item) item.disabled = true;
        });
      }).catch(e => {
        console.log(e);
      });
    },
    // 客户等级
    queryClientLevel() {
      getLevelList().then(res => {
        const result = res && res.data || [];
        result.forEach(item => {
          item.label = item.name;
          item.value = item.name;
        });
        this.clientLevelOptions = result;
      }).catch(e => {
        console.log(e);
      });
    },
    delCustomer(id) {
      showModal('是否删除该客户？', '', {
        center: true,
        showClose: true
      }).then(() => {
        delClient(id).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.list.total) {
              this.page--;
            }
            this.resetItemSelected(id);
            this.fetchData();
          }
        });
      });
    },
    toContact() {
      this.$router.push({
        name: 'contact'
      });
    },
    handleCreate(withClientName = '') {
      if (withClientName === 1 && !this.hasRouteAuth('crm:customer:add')) {
        ElMessage.warning('没有相关权限，请联系管理员！');
        return;
      }
      const params = withClientName === 1 ? { clientName: this.preciseData[0].clientName } : {};
      this.$router.push({
        name: 'createCustomer',
        params
      });
    },
    handelSales(item) {
      if (!item.sale || !item.saleIds) return null;
      const sales = item.sale.split(',');
      const saleIds = item.saleIds.split(',');
      if (saleIds.length !== sales.length) return null;
      return sales.map((i, index) => {
        return {
          userName: i,
          id: saleIds[index]
        };
      });
    },
    toCreateApproval() {
      this.$refs.CreateApprovalRef.openDialog();
    },
    openEditLevel(data) {
      this.$refs.levelInfoRef.openDialog(LEVEL_CHANGE_TYPE.LEVEL, data);
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.customer {
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
  }
  & ::v-deep {
    .pointer {
      cursor: pointer;
    }
    .cell-bg-box > .cell {
      height: 21px;
    }
    .mode-switch-container {
      box-shadow: none !important;
    }
  }
  .opeator-bar {
    position: absolute;
    right: 0;
    top: 0;
    display: flex;
    align-items: center;
  }
  .progress-cell {
    ::v-deep .el-progress__text {
      font-size: 14px !important;
      color: #333;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      max-width: 56px;
    }
  }
  .dot {
    width: 4px;
    height: 4px;
    border-radius: 50%;
    margin-right: 5px;
    $statusBg: #aeb6c7 -1, #31CC9C 0, #ff4e5f 1;
    @each $c, $i in $statusBg {
      &.color-#{$i} {
        background: $c;
      }
    }
  }
}
/* .customer-eidt-tooltip {
  padding: 5px 10px;
  .popper__arrow {
    top: 6px !important;
  }
} */
.search-resource {
  cursor: pointer;
  width: 15px;
  position: relative;
  top: 2px;
  visibility: hidden;
  display: inline-block;
  margin-left: 3px;
}

.resource-name-container {
  display: flex;
  .resource-name {
    display: inline-block;
    color: #406EFF;
  }
  &:hover {
    color: #406EFF;
    .search-resource {
      visibility: visible;
    }
  }
}
.el-dropdown-link {
  display: block;
  position: relative;
  padding-left:6px;
  margin-left: 6px;
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    margin-top: -7px;
    width: 1px;
    background: #ddd;
    height: 14px;
  }
}
.precise-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  p {
    margin: 0;
  }
  .precise-img-tip {
    margin-bottom: 16px;
    img {
      width: 140px;
      height: 140px;
    }
    p {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }
  }
  .precise-data {
    width: 872px;
    height: 160px;
    background: #fafafc;
    border: 1px solid #ebeefd;
    border-radius: 8px;
    padding: 12px 8px;
    .precise-text {
      font-size: 12px;
      color: #666;
      .light-text {
        color: #406eff;
        cursor: pointer;
        text-decoration: underline;
      }
      .gray-text {
        color: #999;
      }
    }
    .precise-table {
      margin-top: 8px;
      padding: 8px;
      background: #ffffff;
      border-radius: 8px;
    }
  }
}
</style>
<style lang="scss">
.select-group {
  .el-select__tags-text {
    min-width: 30px;
  }
  .el-tag__close {
    flex-shrink: 0;
    right: -2px !important;
  }
  .custom-mul-select {
    .el-select__tags>span {
      width: 100%;
    }
  }
  .custom-mul-select:hover {
    .el-select__tags-text {
      padding-right: 10px !important;
    }
  }
}
</style>

